<template>
  <div class="login_box">
    <!-- 登录页 -->
    <div class="login_page" v-if="loginType">
      <div class="login_logo">
        <img src="../assets/img/loginLogo.png" alt="" />
      </div>

      <!-- 表单 -->
      <div class="login_form">
        <div class="login_input">
          <input type="text" placeholder="输入手机号" v-model="loginForm.phone"
            @change="validatePhone"/>
        </div>
        <div class="login_input">
          <input type="password" placeholder="输入密码"  v-model="loginForm.password"
            @change="validatePassword" />
        </div>

        <div class="login_options">
          <input type="checkbox" name="user" id="user" v-model="loginForm.agreement" />
          <label for="user">用户协议</label>

          <p style="margin-left: 22%" @click="handleForgotPwd">忘记密码？</p>
          <p @click="toRegister()">前往注册</p>
        </div>

        <div class="login_btn" @click="handleLogin" :class="{ disabled: isSubmitting }">
          <span v-if="!isSubmitting">登录</span>
          <van-loading v-if="isSubmitting" size="16" color="#fff" />
        </div>
      </div>

      <img class="wx_icon" src="../assets/img/wx.png" alt="" />

      <p class="copyright">@版权归大喇叭实训基地所有</p>
    </div>

    <!-- 注册页 -->
    <div class="register_box" v-if="!loginType">
     <div class="login_logo">
        <img src="../assets/img/loginLogo.png" alt="" />
      </div>

      <!-- 表单 -->
      <div class="login_form">
      <div class="head_portrait">
      <van-uploader :after-read="fileBig" :before-read="checkAvatarSize" :disabled="uploading">
  <van-button icon="plus" type="primary">
  <img :src="headerPortraitUrl || '../assets/img/my.png'" alt="用户头像" />
  </van-button>
</van-uploader>
      </div>
      <div class="login_input">
          <input type="text" placeholder="输入昵称" v-model="registerForm.nickname"
            @change="validateNickname" />
        </div>
        <div class="login_input">
          <input type="text" placeholder="输入手机号" v-model="registerForm.phone"
            @change="validateRegisterPhone" />
        </div>
        <div class="login_input">
          <input type="password" placeholder="输入密码" v-model="registerForm.password"
            @change="validateRegisterPassword" />
        </div>
         <div class="login_numbers">
          <input type="text" placeholder="输入编号" v-model="registerForm.code" 
                 @change="validateCode" />
          <img src="../assets/img/scan.png" alt="" @click="handleScan" />
        </div>

        <div class="login_options">
          <input type="radio" name="user" id="man" value="male" v-model="registerForm.gender" />
          <label for="man">男</label>
          <input type="radio" name="user" id="woman" value="female" v-model="registerForm.gender" />
          <label for="woman">女</label>

          <p style="margin-left: 35%" @click="toRegister()">已有账号？前往登录</p>
        </div>

        <div class="login_btn" @click="handleRegister" :class="{ disabled: isSubmitting }">
          <span v-if="!isSubmitting">登录</span>  <!-- 保留原文字，尽管是注册按钮 -->
          <van-loading v-if="isSubmitting" size="16" color="#fff" />
        </div>
      </div>

      <p class="copyright">@版权归大喇叭实训基地所有</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from "vue";
import { uploadFile } from '../api/issue';
import { logi,regist } from '../api/login';
import { showNotify, Toast } from 'vant';
import {useRouter} from 'vue-router'


// 页面状态
const loginType = ref(true);
const isSubmitting = ref(false); // 提交加载状态
const uploading = ref(false); // 头像上传状态
const router=useRouter()
const jump=(url)=>{
  router.push(url);
}


// 表单数据
const loginForm = reactive({
  phone: '',
  password: '',
  agreement: false
});

const registerForm = reactive({
  nickname: '',
  phone: '',
  password: '',
  code: '',
  gender: 'male'
});

// 头像处理
const header_portrait = ref([]);
const headerPortraitUrl = ref('');
const urlItem = ref([]);

// 页面切换
const toRegister = () => {
  loginType.value = !loginType.value;
};

// 头像上传处理
const checkAvatarSize = (file) => {
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (file.size > maxSize) {
    showNotify({ type: 'danger', message: '图片大小不能超过5MB' });
    return false;
  }
  return true;
};

const fileBig = (file) => {
  uploading.value = true;
  
  // 本地预览
  const reader = new FileReader();
  reader.onload = (e) => {
    headerPortraitUrl.value = e.target.result;
  };
  reader.readAsDataURL(file.file);
  
  // 准备上传
  const formData = new FormData();
  formData.append('file', file.file);
  
  // 修正接口调用
  uploadFile(formData).then((res) => {
    console.log(res.msg);
    if (res.code === 200) {
      headerPortraitUrl.value = res.data.url;
      urlItem.value.push(res.data.url);
      showNotify({ type: 'success', message: '头像上传成功' });
    } else {
      showNotify({ type: 'danger', message: res.msg || '头像上传失败' });
    }
  }).catch((error) => {
    console.error('头像上传异常:', error);
    showNotify({ type: 'danger', message: '头像上传异常，请重试' });
  }).finally(() => {
    uploading.value = false;
  });
};

// 表单验证
const validatePhone = () => {
  if (!loginForm.phone) {
    showNotify({ type: 'danger', message: '手机号不能为空' });
    return false;
  }
  const reg = /^1[3-9]\d{9}$/;
  if (!reg.test(loginForm.phone)) {
    showNotify({ type: 'danger', message: '请输入正确的手机号' });
    return false;
  }
  return true;
};

const validatePassword = () => {
  if (!loginForm.password) {
    showNotify({ type: 'danger', message: '密码不能为空' });
    return false;
  }
  return true;
};

const validateNickname = () => {
  if (!registerForm.nickname) {
    showNotify({ type: 'danger', message: '昵称不能为空' });
    return false;
  }
  return true;
};

const validateRegisterPhone = () => {
  if (!registerForm.phone) {
    showNotify({ type: 'danger', message: '手机号不能为空' });
    return false;
  }
  const reg = /^1[3-9]\d{9}$/;
  if (!reg.test(registerForm.phone)) {
    showNotify({ type: 'danger', message: '请输入正确的手机号' });
    return false;
  }
  return true;
};

const validateRegisterPassword = () => {
  if (!registerForm.password) {
    showNotify({ type: 'danger', message: '密码不能为空' });
    return false;
  }
  return true;
};

// 登录处理
const handleLogin = async () => {
  // 全量验证
  const isPhoneValid = validatePhone();
  const isPwdValid = validatePassword();
  const isAgreementValid = loginForm.agreement;
  
  if (!isAgreementValid) {
    showNotify({ type: 'danger', message: '请同意用户协议' });
    return;
  }
  
  if (!isPhoneValid || !isPwdValid) return;
  
  try {
    
    // 修正登录接口调用
    logi({
       tel: loginForm.phone,
      pass: loginForm.password
    }).then((res)=>{
  console.log(res);

if (res.code ===1) {
  console.log(123);
    showNotify({ type: 'success', message: res.msg });
      // 登录成功后的操作，如跳转首页
      jump('/home')
      
    } else {
  console.log(456);

    showNotify({ type: 'danger', message: res.msg });
    }
    })  
    
  } catch (error) {
  console.log(789);

    showNotify({ type: 'danger', message: '登录失败' });
  } 
};



// 其他功能
const handleForgotPwd = () => {
  showNotify({ type: 'danger', message: '忘记密码功能开发中...' });
};

const handleScan = () => {
  showNotify({ type: 'info', message: '扫码功能开发中...' });
};
</script>

<style scoped>
/* 登录页 */
.login_page,.register_box {
  width: 100%;
  height: 98vh;
  padding-top: 4%;
  background-image: url(../assets/img/loginbackg.jpg);
  background-size: 100% 100%;
}
.login_logo {
  width: 60%;
  height: 150px;
  margin: auto;
  > img {
    width: 100%;
    height: 150px;
  }
}

/* 登录页表单 */
.login_form {
  width: 90%;
  /* height: 240px; */
  margin: auto;
  margin-top: 6%;
  padding-top: 2%;
  border-radius: 5px;
  padding-bottom:4%;
  background-color: rgba(255, 255, 255, 0.3);
}

.login_input {
  width: 90%;
  height: 40px;
  background-color: #fff;
  margin: auto;
  margin-top: 6%;
  padding-left: 1%;
  display: flex;
  align-items: center;
  > input {
    width: 100%;
    border: none;
    outline: none;
  }
}

/* 用户协议+忘记密码+注册 */
.login_options {
  width: 90%;
  height: 40px;
  display: flex;
  align-items: center;
  font-size: 14px;
  margin: auto;
  > p {
    margin-left: 10px;
    color: #2a82e4;
  }
}

/* 登录 */
.login_btn {
  width: 90%;
  height: 40px;
  margin: auto;
  margin-top: 10px;
  color: white;
  border-radius: 8px;
  background-color: #2a82e4;
  display: flex;
  justify-content: center;
  align-items: center;
}

.wx_icon {
  width: 50px;
  height: 50px;
  margin-left: 40%;
  /* margin-top: 20%; */
  position: fixed;
  bottom: 10%;
}

/* 版权 */
.copyright {
  width: 100%;
  display: flex;
  justify-content: center;
  color: #6e6e6e;
  font-size: 14px;
  position: fixed;
  bottom: 1%;
}

/* 注册页 */
.login_numbers{
     width: 90%;
  height: 40px;
  background-color: #fff;
  margin: auto;
  margin-top: 6%;
  padding-left: 1%;
  display: flex;
  align-items: center;
  > input {
    width: 86%;
    border: none;
    outline: none;
  }
  > img{
    width: 30px;
    height: 30px;

  }
}

.register_box{
  >.login_logo{
    >img{
       width: 80%;
       height: 120px;
       margin-left: 10%;
    }
  }
}

.head_portrait{
  display: flex;
  justify-content: center;
   img{
  width: 80px;
  height: 80px;
      border-radius:50%;
}
}


</style>